//
//  ViewController.m
//  TestReader
//
//  Created by 李雷川 on 2018/1/28.
//  Copyright © 2018年 李雷川. All rights reserved.
//

#import "ViewController.h"
#import "RequestConfig.h"
#import "CBCBookDetailViewController.h"
#import "iTools.h"

@interface ViewController ()<UIWebViewDelegate>
@property(nonatomic, strong)UIWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view addSubview:self.webView];
    NSString *urlstr = @"http://and.cbchot.com/android/book/hot";
    //生成联网请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstr]];
    
    //设置header
    [request addValue:[RequestConfig ContentType] forHTTPHeaderField:@"Content-Type"];
    [request addValue:[RequestConfig UserAgent] forHTTPHeaderField:@"User-Agent"];
    [request addValue:[RequestConfig getXClient] forHTTPHeaderField:@"X-Client"];
    
    request.cachePolicy = NSURLRequestReloadIgnoringCacheData;//忽略本地缓存
    [self.webView loadRequest:request];
    
}

-(UIWebView *)webView{
    if(_webView == nil){
        _webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
        _webView.delegate = self;
    }
    return _webView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 * 页面点击事件
 */
- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    //点击或表单提交的处理
    if (navigationType == UIWebViewNavigationTypeLinkClicked || navigationType == UIWebViewNavigationTypeFormSubmitted)
    {
        //获取路径
        NSString * url = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //判断是否为自定义标签
        if ([url hasPrefix:@"cbchot:bookDetails"]) {
            NSArray *components = [url componentsSeparatedByString:@"|"];
            if([components count] == 3){
                NSString *bookID = components[1];
                NSString *url = [iTools getHttpUrl:components.lastObject];
                CBCBookDetailViewController *bookDetailViewController = [[CBCBookDetailViewController alloc] initWithUrl:url];
                bookDetailViewController.bookID = bookID;
                [self.navigationController pushViewController:bookDetailViewController animated:YES];
            return NO;
        }
        
        }
    }
    return YES;
}

@end
